//
//  ListenTestViewController.m
//  xpkc
//
//  Created by wanmeizty on 14-8-18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "ListenTestViewController.h"
#import "MJRefresh.h"
@interface ListenTestViewController ()
{
//    NSMutableArray *_columnListArray;
    NSString *_idString;
//    NSString *_timeString;
//    NSString *_url1;
    NSInteger _tag;
    ListenTestTableViewCell *_cell;
     int pageNum;
}
@end

@implementation ListenTestViewController{
    BOOL refresh;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        self.tabBarItem.image = [UIImage imageNamed:@"listentest"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"listentest_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    //初始化数据数组
    _videoListArray = [[NSMutableArray alloc]init];
 
    if (IsIOS7) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
    _listenTestView=[[ListenTestView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_listenTestView];

    _listenTestView.tableView.delegate=self;
    _listenTestView.tableView.dataSource=self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshWithHeader:)];
    _listenTestView.tableView.header = header;
    MJRefreshAutoNormalFooter *footer = [[MJRefreshAutoNormalFooter alloc]init];
    [footer setRefreshingTarget:self refreshingAction:@selector(requestMoreWithFooter:)];
    _listenTestView.tableView.footer = footer;

    [self requestNewslistWithPage:0];
    
    logdebug(@"%d",[self shouldAutorotate]);
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self supportedInterfaceOrientations];
}



#pragma mark - request
//  请求分类下列表数据
- (void)requestNewslistWithPage:(int)page{
    pageNum = page;
    _idString = [NSString stringWithFormat:@"%ld",(long)self.typeId];
    NSString *module = @"openCourse";
    NSString *interface = @"videolist";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"columnid":_idString,@"pagecode":[NSString stringWithFormat:@"%d",page]};
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSArray *info = [dic objectForKey:@"info"];
                if (page == 0) {
                    [_videoListArray removeAllObjects];
                }

                for (NSDictionary *video in info) {
                    ListenTestModel *model=[[ListenTestModel alloc]init];
                    model.videoId=[video objectForKey:@"id"];
//                    model.classname=[video objectForKey:@"classname"];
                    model.title=[video objectForKey:@"title"];
                    model.teacher=[video objectForKey:@"teacher"];
                    model.imageUrl=[video objectForKey:@"image"];
                    model.duration=[video objectForKey:@"duration"];
                    model.play_num=[video objectForKey:@"play_num"];
                    model.score=[video objectForKey:@"score"];
                    [_videoListArray addObject:model];
                }
          [_listenTestView.tableView.header endRefreshing];
          [_listenTestView.tableView.footer endRefreshing];
      
        [hud hide:YES];
        [_listenTestView.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        logdebug(@"%@",error.localizedDescription);
        [_listenTestView.tableView.header endRefreshing];
        [_listenTestView.tableView.footer endRefreshing];
        [hud hide:YES];
    }];
}

- (void)refreshWithHeader:(MJRefreshHeader *)header{
    [self requestNewslistWithPage:0];
}
- (void)requestMoreWithFooter:(MJRefreshFooter *)footer{
    [self requestNewslistWithPage:pageNum+1];
}


//Cell行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _videoListArray.count;
}
//Cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 94;
}
//Cell内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identified=@"Cell";
    _cell=[tableView dequeueReusableCellWithIdentifier:identified];
    if (_cell==nil) {
        _cell=[[ListenTestTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identified];
    }
    if (_videoListArray.count == 0) {
        return _cell;
    }
    /**
     *   设置cell的背景
     */
    if (indexPath.row%2 == 0) {
        _cell.backgroundColor = [UIColor whiteColor];
    }else{
        _cell.backgroundColor = BGColor;
    }
    /**
     *   cell赋值
     */
    ListenTestModel *model=[_videoListArray objectAtIndex:indexPath.row];
    if ([model.imageUrl isKindOfClass:[NSNull class]]) {
    } else {
        [_cell.left_image setImageWithURL:[NSURL URLWithString:model.imageUrl]];
    }
    if ([model.title isKindOfClass:[NSNull class]]) {
    } else {
        _cell.title_Label.text=model.title;
    }
    if ([model.classname isKindOfClass:[NSNull class]]) {
    } else {
        //_cell.class_Label.text=model.classname;
    }
    if ([model.teacher isKindOfClass:[NSNull class]]) {
    } else {
        _cell.teacher_Label.text=model.teacher;
    }
//    _cell.name_Label.text=@"讲师：";
//	_cell.timeName_Label.text = @"时长：";
    if ([model.duration isKindOfClass:[NSNull class]]) {
    }else{
    _cell.time_Label.text=[NSString stringWithFormat:@"%@分钟",model.duration];
    }
    if ([model.play_num isKindOfClass:[NSNull class]]) {
    }else{
        _cell.viewLabel.text=[NSString stringWithFormat:@"%@人观看",model.play_num];
    }
	[_cell setStarImageViewWithNumber:[NSString stringWithFormat:@"%@",model.score]];
    return _cell;
}


/**
 *   页面跳转
 *
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _myNumber = indexPath.row;
    ListenTestModel *model = [_videoListArray objectAtIndex:indexPath.row];
    ListenTestInfoViewController * videoInfoVC = [[ListenTestInfoViewController alloc]init];
    videoInfoVC.videoListArray = _videoListArray;
    videoInfoVC.myNumber = _myNumber;
    videoInfoVC.videoId = model.videoId;
//    videoInfoVC.title = self.className;
    videoInfoVC.nextArrray = _videoListArray;
    videoInfoVC.nowVideo = indexPath.row;
    videoInfoVC.hidesBottomBarWhenPushed = YES;
    
    
    videoInfoVC.image=model.imageUrl;
    videoInfoVC.titles=model.title;
    videoInfoVC.teacher=model.teacher;
    videoInfoVC.duration=[NSString stringWithFormat:@"%@",model.duration];
    videoInfoVC.score=[NSString stringWithFormat:@"%@",model.score];
    videoInfoVC.play_num=[NSString stringWithFormat:@"%@",model.play_num];

    
    
    [videoInfoVC setTitle:[NSString stringWithFormat:@"%@公开课",self.className]];
   
    
    [self.navigationController pushViewController:videoInfoVC animated:YES];
    if (IsIOS7) {
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
